package com.lengxf.pay.common.service;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.crypto.CryptoException;
import cn.hutool.http.HttpConfig;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.lengxf.pay.common.config.PayConfig;
import com.lengxf.pay.common.http.PayRequestTemplate;
import com.lengxf.pay.common.sign.SignEnum;
import com.lengxf.pay.common.sign.service.SignService;
import lombok.Getter;
import lombok.Setter;

@Getter
public abstract class AbstractBasePayService<PC extends PayConfig> implements BasePayService {

    protected static final Log log = LogFactory.get();

    private static final String DEFAULT_CHARACTER = "UTF-8";

    @Setter
    private PC payConfig;

    protected PayRequestTemplate payRequestTemplate;

    public AbstractBasePayService(PC payConfig) {
        this(payConfig, HttpConfig.create());
    }

    public AbstractBasePayService(PC payConfig, HttpConfig httpConfig) {
        payRequestTemplate = new PayRequestTemplate(httpConfig);
        setPayConfig(payConfig);
    }

    protected String createSign(String content) {
        return createSign(content, DEFAULT_CHARACTER);
    }

    protected String createSign(String content, String characterEncoding) {
        SignService signService = ReflectUtil.newInstance(getPayConfig().reqSignType().getSignService());
        return signService.sign(content, getPayConfig().keyPrivate(), characterEncoding);
    }

    protected void signVerify(PayConfig payConfig, String content, String sign) {
        signVerify(payConfig.resSignType(), content, sign, payConfig.keyPublic(), DEFAULT_CHARACTER);
    }

    protected void signVerify(SignEnum signType, String content, String sign, String keyPublic, String characterEncoding) {
        try {
            SignService signService = ReflectUtil.newInstance(signType.getSignService());
            Boolean verify = signService.verify(content, sign, keyPublic, characterEncoding);
            if (!verify) {
                throw new CryptoException("验签失败");
            }
        } catch (Exception e) {
            log.error("验签失败 : ", e);
            throw e;
        }
    }


}
